<!--
  * 角色 员工 列表
  *
  * @Author:    zhoujk
  * @Date:      2025-02-09 22:34:00
  *
-->
<template>
  <a-modal v-model:open="visible" :width="900" title="移除人员" @cancel="closeModal" :footer="null">
    <div>
      <div class="header">
        <div>
          关键字：
          <a-input style="width: 250px" v-model:value="queryForm.keywords" placeholder="姓名/手机号/登录账号" />
          <a-button class="button-style" v-if="selectRoleId" type="primary" @click="onSearch">搜索</a-button>
          <a-button class="button-style" v-if="selectRoleId" type="default" @click="resetQueryRoleUser">重置</a-button>
        </div>

        <!--<div>-->
        <!--  <a-button class="button-style" v-if="selectRoleId" type="primary" danger @click="batchDelete" v-privilege="'system:role:user:batch:delete'"-->
        <!--    >批量移除-->
        <!--  </a-button>-->
        <!--</div>-->
      </div>

      <a-table
        :loading="tableLoading"
        :dataSource="tableData"
        :columns="columns"
        :pagination="false"
        :scroll="{ y: 400 }"
        rowKey="id"
        :row-selection="{ selectedRowKeys: selectedRowKeyList, onChange: onSelectChange }"
        size="small"
        bordered
      >
        <template #bodyCell="{ text, record, column }">
          <template v-if="column.dataIndex === 'status'">
            <a-tag :color="text ? 'processing' : 'error'">{{ text ? '启用' : '禁用' }}</a-tag>
          </template>
          <template v-else-if="column.dataIndex === 'sex'">
            <span>{{ $smartEnumPlugin.getDescByValue('ZZB_SEX_ENUM', text) }}</span>
          </template>
          <template v-if="column.dataIndex === 'operate'">
            <a @click="deleteUserRole(record.id)" v-privilege="'system:user:role:delete'">移除</a>
          </template>
        </template>
      </a-table>
      <div class="smart-query-table-page">
        <a-pagination
          showSizeChanger
          showQuickJumper
          show-less-items
          :pageSizeOptions="PAGE_SIZE_OPTIONS"
          :defaultPageSize="queryForm.pageSize"
          v-model:current="queryForm.pageNo"
          v-model:pageSize="queryForm.pageSize"
          :total="total"
          @change="queryRoleUser"
          @showSizeChange="queryRoleUser"
          :show-total="showTableTotal"
        />
      </div>
    </div>
  </a-modal>
</template>
<script setup>
  import { message, Modal } from 'ant-design-vue'
  import { computed, onMounted, reactive, ref, watch } from 'vue'
  import { roleApi } from '/src/api/system/b-operation/role-api'
  import { PAGE_SIZE, showTableTotal, PAGE_SIZE_OPTIONS } from '/src/constants/common-const'
  import { SmartLoading } from '/src/components/framework/smart-loading'
  import { smartSentry } from '/src/lib/smart-sentry'
  import { userApi } from '/src/api/system/b-operation/user-api.js'

  // ----------------------- 以下是字段定义 emits props ---------------------
  defineExpose({
    showModal,
  })

  // ----------------------- modal  显示与隐藏 ---------------------

  const visible = ref(false)
  const selectRoleId = ref('')

  async function showModal(roleId) {
    selectRoleId.value = roleId
    visible.value = true
    onSearch()
  }

  function closeModal() {
    Object.assign(queryForm, defaultQueryForm)
    visible.value = false
  }

  // ----------------------- 员工列表：显示和搜索 ------------------------
  watch(
    () => selectRoleId.value,
    () => queryRoleUser(),
  )

  onMounted(queryRoleUser)

  const defaultQueryForm = {
    pageNo: 1,
    pageSize: PAGE_SIZE,
    roleId: undefined,
    keywords: undefined,
    showRoleFlag: false,
  }
  // 查询表单
  const queryForm = reactive({ ...defaultQueryForm })
  // 总数
  const total = ref(0)
  // 表格数据
  const tableData = ref([])
  // 表格loading效果
  const tableLoading = ref(false)

  function resetQueryRoleUser() {
    queryForm.keywords = ''
    queryRoleUser()
  }

  function onSearch() {
    queryForm.pageNo = 1
    queryRoleUser()
  }

  async function queryRoleUser() {
    try {
      tableLoading.value = true
      queryForm.roleId = selectRoleId.value
      let res = await userApi.page(queryForm)
      tableData.value = res.data
      total.value = res.total
    } catch (e) {
      smartSentry.captureError(e)
    } finally {
      tableLoading.value = false
    }
  }

  const columns = reactive([
    {
      title: '姓名',
      dataIndex: 'name',
    },
    {
      title: '手机号',
      dataIndex: 'phone',
    },
    {
      title: '登录账号',
      dataIndex: 'no',
    },
    {
      title: '部门',
      dataIndex: 'departName',
    },
    {
      title: '状态',
      dataIndex: 'status',
    },
    {
      title: '操作',
      dataIndex: 'operate',
      width: 60,
    },
  ])

  // ----------------------- 移除成员 ---------------------------------
  // 删除角色成员方法
  async function deleteUserRole(userId) {
    Modal.confirm({
      title: '提示',
      content: '确定要删除该角色成员么？',
      okText: '确定',
      okType: 'danger',
      async onOk() {
        SmartLoading.show()
        try {
          await userApi.deleteUserRole({ userId: userId, roleId: selectRoleId.value })
          message.success('移除成功')
          await queryRoleUser()
        } catch (e) {
          smartSentry.captureError(e)
        } finally {
          SmartLoading.hide()
        }
      },
      cancelText: '取消',
      onCancel() {},
    })
  }

  // ----------------------- 批量删除 ---------------------------------

  const selectedRowKeyList = ref([])
  const hasSelected = computed(() => selectedRowKeyList.value.length > 0)

  function onSelectChange(selectedRowKeys) {
    selectedRowKeyList.value = selectedRowKeys
  }

  // 批量移除
  function batchDelete() {
    if (!hasSelected.value) {
      message.warning('请选择要删除的角色成员')
      return
    }
    Modal.confirm({
      title: '提示',
      content: '确定移除这些角色成员吗？',
      okText: '确定',
      okType: 'danger',
      async onOk() {
        SmartLoading.show()
        try {
          let params = {
            userIdList: selectedRowKeyList.value,
            roleId: selectRoleId.value,
          }
          await roleApi.batchRemoveRoleUser(params)
          message.success('移除成功')
          selectedRowKeyList.value = []
          await queryRoleUser()
        } catch (e) {
          smartSentry.captureError(e)
        } finally {
          SmartLoading.hide()
        }
      },
      cancelText: '取消',
      onCancel() {},
    })
  }
</script>

<style scoped lang="less">
  .header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin: 20px 0;
  }

  .button-style {
    margin: 0 10px;
  }
</style>
